/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JCatalogKeyBoardDialog.java
 *
 * Created on 2009-9-12, 13:19:23
 */

package cn.ekuma.epos.qkorder.dialog;

import cn.ekuma.epos.bean.util.ProductInfoHelper;
import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.epos.qkorder.JPanelOrder;
import cn.ekuma.swing.dialog.AbstractKeyBoardJDialog;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.JMessageDialog;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.ImageUtils;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.bean.ProductExt;
import com.openbravo.pos.catalog.JCatalog;
import com.openbravo.pos.panels.JPanelButtons;
import com.openbravo.pos.util.ThumbNailBuilder;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.KeyStroke;

/**
 *
 * @author Administrator
 */
public class JCatalogDialog extends AbstractKeyBoardJDialog implements ActionListener{


    private boolean isSignSelected;

    /** Creates new form JCatalogKeyBoardDialog */
    public JCatalogDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
       
    }

     /** Creates new form JTicketsBagSharedList */
    private  JCatalogDialog(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
    }

    ProductListModel productListModel;
    private ThumbNailBuilder tnbbutton;
    private boolean isOK;
    JCatalog jcatalog;
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        m_jButtonOK = new javax.swing.JButton();
        m_jButtonCancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(new java.awt.BorderLayout());
        jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);

        jPanel4.setPreferredSize(new java.awt.Dimension(140, 0));
        jPanel4.setLayout(new java.awt.BorderLayout());

        jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.LINE_AXIS));

        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        m_jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
        m_jButtonOK.setFocusPainted(false);
        m_jButtonOK.setFocusable(false);
        m_jButtonOK.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonOK.setRequestFocusEnabled(false);
        m_jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonOKActionPerformed(evt);
            }
        });
        jPanel5.add(m_jButtonOK);

        m_jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
        m_jButtonCancel.setFocusPainted(false);
        m_jButtonCancel.setFocusable(false);
        m_jButtonCancel.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonCancel.setRequestFocusEnabled(false);
        m_jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonCancelActionPerformed(evt);
            }
        });
        jPanel5.add(m_jButtonCancel);

        jPanel3.add(jPanel5);

        jPanel4.add(jPanel3, java.awt.BorderLayout.SOUTH);

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setPreferredSize(new java.awt.Dimension(70, 100));

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jList1.setPreferredSize(new java.awt.Dimension(70, 85));
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jPanel4.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel4, java.awt.BorderLayout.EAST);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-522)/2, (screenSize.height-502)/2, 522, 502);
    }// </editor-fold>//GEN-END:initComponents

    private void m_jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonOKActionPerformed
          enterKeyProc();
}//GEN-LAST:event_m_jButtonOKActionPerformed

    private void m_jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonCancelActionPerformed
          escapeKeyProc();
}//GEN-LAST:event_m_jButtonCancelActionPerformed

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
        if(evt.getClickCount()==2){
            deleteKeyProc();
        }
    }//GEN-LAST:event_jList1MouseClicked

    public static JCatalogDialog newJDialog(JPanelOrder orderPanel,I_DataLogicSales dlSales,JPanelButtons m_jbtnconfig,boolean isSign) throws BasicException {
        Window window = getWindow(orderPanel);
        JCatalogDialog mydialog;
        if (window instanceof Frame) {
            mydialog = new JCatalogDialog((Frame) window, true);
        } else {
            mydialog = new JCatalogDialog((Dialog) window, true);
        }
        mydialog.init(dlSales,m_jbtnconfig,isSign);
        return mydialog;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton m_jButtonCancel;
    private javax.swing.JButton m_jButtonOK;
    // End of variables declaration//GEN-END:variables

    
    private void init(I_DataLogicSales dlSales,JPanelButtons m_jbtnconfig,boolean isSign) throws BasicException{
         initComponents();
         isOK=false;
         isSignSelected=isSign;
        productListModel=new ProductListModel();
        jcatalog=new JCatalog(dlSales,
                "true".equals(m_jbtnconfig.getProperty("pricevisible")),
                "true".equals(m_jbtnconfig.getProperty("taxesincluded")),
                 Integer.parseInt(m_jbtnconfig.getProperty("img-width", "64")),
                 Integer.parseInt(m_jbtnconfig.getProperty("img-height", "54")));
         jcatalog.addActionListener(this);
         jcatalog.loadCatalog();
         jPanel2.add(jcatalog, java.awt.BorderLayout.CENTER);
         jList1.setModel(productListModel);
         jList1.setCellRenderer(new SmallProductRenderer());
         jList1.setPreferredSize(new Dimension(Integer.parseInt(m_jbtnconfig.getProperty("img-width", "64")),0));
         tnbbutton = new ThumbNailBuilder(Integer.parseInt(m_jbtnconfig.getProperty("img-width", "64")),
                                          Integer.parseInt(m_jbtnconfig.getProperty("img-height", "54")),
                                          "com/openbravo/images/package.png");
         KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
         ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                try {
                    jcatalog.loadCatalog();
                } catch (BasicException e) {
                  JMessageDialog.showMessage(JCatalogDialog.this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
                  escapeKeyProc();
                }
            }
        };
        rootPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
         stroke = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
        actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                    deleteKeyProc();
            }
        };
        rootPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        setSizeFullOfScreen(this);
    }


    public static final Toolkit toolkit = Toolkit.getDefaultToolkit();
     /**
      * 将window全屏化,对Window,Frame,Dialog,JWindow,JFrame,JDialog有效
      * @param window 全屏化的window
      * @see Window,Frame,Dialog,JWindow,JFrame,JDialog
      */
     public static void setSizeFullOfScreen(Window window) {
         Dimension screenSize = toolkit.getScreenSize();
         window.setBounds(0, 0, screenSize.width, screenSize.height);
     }


    private void addSelectedProduct(ProductExt prod){
        productListModel.add(prod);
        if(isSignSelected){
          enterKeyProc();
        }
    }

   private void deleteKeyProc() {
          int index=jList1.getSelectedIndex();
          if(index>=0&&index<productListModel.getSize())
              productListModel.remove(index);
   }

    private class ProductListModel extends AbstractListModel {
        private java.util.List m_aCategories;
        public ProductListModel() {
            m_aCategories = new ArrayList();
        }
        public int getSize() {
            return m_aCategories.size();
        }
        public Object getElementAt(int i) {
            return m_aCategories.get(i);
        }

        public void add(ProductExt prod) {
           m_aCategories.add(prod);
           this.fireIntervalAdded(prod, getSize(), getSize());
        }

        public void reset(){
            m_aCategories = new ArrayList();
            fireContentsChanged(this, 0, 0);
        }

        private List<ProductExt> getProductList() {
            return m_aCategories;
        }

        private void remove(int index) {
           fireIntervalRemoved(m_aCategories.get(index), index, index);
           m_aCategories.remove(index);
        }
    }


     private class SmallProductRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, null, index, isSelected, cellHasFocus);
            ProductExt cat = (ProductExt) value;
            //setText(cat.getName());
            setIcon(new ImageIcon(tnbbutton.getThumbNailText(ImageUtils.readImage(cat.getImage()),getProductLabel(cat))));
            return this;
        }
    }
    

    public boolean isIsOK() {
        return isOK;
    }

    public List<ProductExt> getProducts() {
        return this.productListModel.getProductList();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        ProductExt prod=(ProductExt)e.getSource();
        addSelectedProduct(prod);
    }


    private String getProductLabel(ProductExt product) {
        if (product.getPriceSell()>0) {
                return "<html><center>" + product.getName() + "<br>" + ProductInfoHelper.printPriceSell(product);
        } else {
            return product.getName();
        }
    }

    @Override
    protected void enterKeyProc() {
        if(getProducts().size()>0)
            isOK=true;
         dispose();
    }

    @Override
    protected void escapeKeyProc() {
         dispose();
    }

    @Override
    protected void upKeyProc() {
          jcatalog.selectUp();
    }

    @Override
    protected void downKeyProc() {
        jcatalog.selectDown();
    }

    public boolean isOK() {
        return isOK;
    }

    public void reset() {
        isOK=false;
        productListModel.reset();
    }
}
